from pathlib import Path
import json
import time
import uuid
import sys
from dataclasses import dataclass
from typing import Optional

# 简化导入方式
try:
    # 先尝试直接导入
    from reqapi.api import BaseApi, ApiConfig
    from laste_device_id_gen_and_verify import create_device_id
except ImportError:
    # 如果直接导入失败，尝试从当前目录导入
    from ..api import BaseApi, ApiConfig
    from .laste_device_id_gen_and_verify import create_device_id

@dataclass
class DeviceInfoRequest:
    """设备信息请求"""
    appVersion: str
    data: dict
    src: str
    time: int
    uid: str
    uk: str
    userId: int
    version: str
    Sessionid: str
    
    @classmethod
    def create_default(cls, device_id: str = None, uk: str = "", user_id: int = 0, android_id: Optional[str] = None):
        """创建默认的设备信息请求
        
        Args:
            device_id: 设备ID，如果不提供则使用空字符串
            uk: UK值，如果不提供则使用空字符串
            user_id: 用户ID，如果不提供则使用0
            android_id: Android ID，如果提供则设置到aid字段
            
        Returns:
            DeviceInfoRequest: 设备信息请求对象
        """
        current_time = int(time.time() * 1000)
        
        # 使用ApiConfig中的方法生成设备数据
        device_data = ApiConfig.generate_device_data()
        
        # 如果提供了Android ID，则设置到aid字段
        if android_id:
            device_data["aid"] = android_id
            print(f"设备信息请求中使用Android ID (aid): {android_id}")
        
        return cls(
            appVersion=ApiConfig.APP_VERSION,
            data=device_data,
            src="android",
            time=current_time,
            uid=str(uuid.uuid4()),
            uk=uk,
            userId=user_id,
            version="v1.0.0",
            Sessionid=device_id or ""
        )

@dataclass
class DeviceInfoResponse:
    """设备信息响应"""
    code: int
    msg: str
    data: Optional[dict]
    
    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建响应对象"""
        return cls(
            code=data.get('code'),
            msg=data.get('msg'),
            data=data.get('data')
        )

class DeviceInfoApi(BaseApi):
    """设备信息API"""
    
    def __init__(self, device_token=None, device_id=None, auth_token=None, uk=""):
        """初始化设备信息API
        
        Args:
            device_token: 设备令牌，如果不提供则使用None
            device_id: 设备ID，如果不提供则使用None
            auth_token: 授权令牌，如果不提供则使用空字符串
            uk: UK值，如果不提供则使用空字符串
        """
        # 初始化基类
        super().__init__(
            device_token=device_token,
            device_id=device_id,
            auth_token=auth_token or "",
            uk=uk
        )
    
    def report_device_info(self, request: DeviceInfoRequest, raise_on_error=False):
        """标准上报设备信息，风格统一，异常和错误码返回 None"""
        endpoint = "/api/app"
        url = f"{self.BASE_URL}{endpoint}"
        request_data = {
            "appVersion": request.appVersion,
            "data": request.data,
            "src": request.src,
            "time": request.time,
            "uid": request.uid,
            "uk": request.uk,
            "userId": request.userId,
            "version": request.version,
            "Sessionid": request.Sessionid
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            code_val = resp_json.get('Code', resp_json.get('code', -1))
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg'))}")
                return None
            if hasattr(DeviceInfoResponse, 'from_dict'):
                return DeviceInfoResponse.from_dict(resp_json)
            return DeviceInfoResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None

    def custom_report_device_info(self, request: DeviceInfoRequest, first_call=False, raise_on_error=False):
        """自定义上报设备信息，可以指定是否是第一次调用
        
        Args:
            request: 设备信息请求对象
            first_call: 是否是第一次调用，如果是则使用特定的请求头
            raise_on_error: 是否在发生错误时抛出异常
            
        Returns:
            DeviceInfoResponse: 设备信息响应对象
        """
        # API端点
        endpoint = "/api/app"
        url = f"{self.BASE_URL}{endpoint}"
        
        # 构建请求数据
        request_data = {
            "appVersion": request.appVersion,
            "data": request.data,
            "src": request.src,
            "time": request.time,
            "uid": request.uid,
            "uk": request.uk,
            "userId": request.userId,
            "version": request.version,
            "Sessionid": request.Sessionid
        }
        
        # 获取请求头
        if first_call:
            # 第一次调用使用特定的请求头
            device_info = {
                "deviceId": "",
                "deviceType": "SM-G9810",
                "hasSteamApp": 0,
                "requestTag": "62F22D09EA415D182C016A8EEF0C60A6",
                "systemName": "Android",
                "systemVersion": "7.1.2"
            }
            
            headers = {
                "host": "api.youpin898.com",
                "devicetoken": "",
                "deviceid": "",
                "requesttag": "EAFF781B42DE752479E24BFD64610E6B",
                "gameid": "730",
                "devicetype": "0",
                "platform": "android",
                "currenttheme": "Light",
                "package-type": "uuyp",
                "content-encoding": "gzip",
                "app-version": "5.28.2",
                "device-info": json.dumps(device_info),
                "apptype": "7",
                "authorization": "Bearer",
                "content-type": "application/json; charset=utf-8",
                "accept-encoding": "gzip",
                "user-agent": "okhttp/3.14.9"
            }
        else:
            # 非第一次调用使用通用请求头，并确保UK值正确设置
            # 先更新self.uk为请求中的UK值，确保common_headers中包含正确的UK
            self.uk = request.uk
            headers = self.common_headers.copy()  # 使用copy()防止污染
            
            # 确保device-info中的deviceId正确设置
            device_info_json = json.loads(headers.get("device-info", "{}"))
            device_info_json["deviceId"] = request.Sessionid
            headers["device-info"] = json.dumps(device_info_json)
        
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            code_val = resp_json.get('Code', resp_json.get('code', -1))
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg'))}")
                return None
            # 若有 from_dict 方法则优先用
            if hasattr(DeviceInfoResponse, 'from_dict'):
                return DeviceInfoResponse.from_dict(resp_json)
            return DeviceInfoResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试设备信息API"""
    try:
        # 获取Android ID
        android_id = ApiConfig.AID
        print(f"使用Android ID: {android_id}")
        
        # 方式1: 无设备ID、无用户信息、无UK的调用
        print("\n===== 方式1: 无设备ID、无用户信息、无UK的调用 =====")
        # 创建API实例，不提供任何参数
        api1 = DeviceInfoApi()
        
        # 创建请求对象，只传入Android ID
        request1 = DeviceInfoRequest.create_default(android_id=android_id)
        
        # 发送请求
        print("发送请求...")
        result1 = api1.report_device_info(request1)
        
        # 打印结果
        print("设备信息上报成功！")
        print(f"响应数据: {result1.data}")
        
        # 方式2: 有设备ID、有用户信息、有UK的调用
        print("\n===== 方式2: 有设备ID、有用户信息、有UK的调用 =====")
        # 使用laste_device_id_gen_and_verify生成设备ID
        device_id = create_device_id(android_id)
        print(f"使用生成的device_id: {device_id}")
        
        # 使用实际的认证信息
        auth_token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjMjQyZTliZGFhYjY0ZGVmODIyMmZjOWU1YjE4OTg2OSIsIm5hbWVpZCI6Ijk1MzQ1NTYiLCJJZCI6Ijk1MzQ1NTYiLCJ1bmlxdWVfbmFtZSI6IumAn-WPkTEzMSIsIk5hbWUiOiLpgJ_lj5ExMzEiLCJ2ZXJzaW9uIjoiejZ0IiwibmJmIjoxNzQzMDY2NTU4LCJleHAiOjE3NDU5NTczNTgsImlzcyI6InlvdXBpbjg5OC5jb20iLCJkZXZpY2VJZCI6Ilo3TGVIN3ZkRFljREFJWUkzL1RWWGZBSCIsImF1ZCI6InVzZXIifQ.w5nYMfuApf5lQdHoH2a3-GTnUo-5w_SpKn3jCjrK38M"
        uk = "5FDFSRFUD0wsn4vgzgeZpQIxPQzgCtMd3SfawJ2FStxg6MCO4d1esVBdyWoCfkr1N"
        user_id = 9534556  # 从认证令牌中提取的用户ID
        
        # 创建API实例，提供所有参数
        api2 = DeviceInfoApi(
            device_token=device_id,
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 创建请求对象，传入所有参数
        request2 = DeviceInfoRequest.create_default(
            device_id=device_id,
            uk=uk,
            user_id=user_id,
            android_id=android_id
        )
        
        # 发送请求
        print("发送请求...")
        result2 = api2.report_device_info(request2)
        
        # 打印结果
        print("设备信息上报成功！")
        print(f"响应数据: {result2.data}")
        
    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()
